﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using RestFullChatAJAX.Models;
using System.Text;
using System.IO;
using System.Threading;
using Newtonsoft.Json.Linq;

namespace RestFullChatAJAX.Controllers
{
    public class YahooActionController : ApiController
    {
        private const String URL_OAUTH_SEND = "http://localhost:53220/api/OAuthMessage";

        // POST api/Message/username?userreceive&message
        public HttpStatusCode PostMessage(String id, [FromBody] MessageSend info)
        {
            int index = IndexManager.FindYahooIndex(id.Trim());
            if (index != -1)
            {
                if (String.IsNullOrEmpty(info.Message))
                {
                    return HttpStatusCode.OK;
                }
                YahooInfo yi = IndexManager.GetYahooInfo(index);
                String urlrequest = String.Format(URL_OAUTH_SEND) + yi.Oauth.getHeader(IndexManager.CONSUMERKEY, IndexManager.CONSUMERKEYSECRECT) + "&toUser=" + info.UserReceive;
                HttpWebRequest Request = HttpWebRequest.Create(urlrequest.Trim()) as HttpWebRequest;
                Request.Method = "POST";
                Request.ContentType = "application/json;charset=utf-8";
                String content = String.Format("\"mess\":\"{0}\"", info.Message);
                content = "{" + content + "}";
                byte[] requestBytes = new UTF8Encoding().GetBytes(content);
                Request.ContentLength = requestBytes.Length;
                using (Stream stream = Request.GetRequestStream())
                {
                    stream.Write(requestBytes, 0, requestBytes.Length);
                }

                using (HttpWebResponse response = Request.GetResponse() as HttpWebResponse)
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        // Create Stream Reader                   
                        return HttpStatusCode.OK;
                    }
                }
            }
            return HttpStatusCode.BadRequest;
        }
    }
}
